package org.mspring.mlog.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.support.TabItem;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Gao Youbo
 * @since 2014-12-22 18:44
 */
@Component
public class TabItemInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView == null) {
            return;
        }
        String parent = "";
        String item = "";
        HandlerMethod method = (HandlerMethod) handler;
        TabItem beanTabItem = method.getBean().getClass().getAnnotation(TabItem.class);
        if (beanTabItem != null) {
            parent = beanTabItem.item();
        }
        TabItem methodTabItem = method.getMethodAnnotation(TabItem.class);
        if (methodTabItem != null) {
            if (StringUtils.isNotBlank(methodTabItem.item())) {
                item = methodTabItem.item();
            }
        }
        if (StringUtils.isBlank(parent)) {
            parent = getParent(item);
        }
        if (StringUtils.isNotBlank(parent) || StringUtils.isNotBlank(item)) {
            modelAndView.getModel().put("_parent_item", parent);
            modelAndView.getModel().put("_item", item);
        }
        super.postHandle(request, response, handler, modelAndView);
    }

    private String getParent(String item) {
        if (StringUtils.length(item) == 3) {
            return StringUtils.left(item, 1);
        } else {
            return StringUtils.left(item, StringUtils.length(item) - 3);
        }
    }
}
